﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlServerCe;
using System.Text.RegularExpressions;
using log4net; 

namespace NetworkAssetManager.DataAcccess
{
    class CreateDatabase
    {
        private static readonly ILog _logger = LogManager.GetLogger(typeof(CreateDatabase));

        public static void VerifyDatabaseExists()
        {
            string connString = NetworkAssetManager.Properties.Settings.Default.NetworkAssetManagerConnectionString;
            _logger.Info("Updating the database");

            using ( SqlCeConnection conn = new SqlCeConnection(connString))
            {
                if ( System.IO.File.Exists(conn.Database) !=true)
                {
                    using (SqlCeEngine engine = new SqlCeEngine(connString))
                    {
                        _logger.Info("Creating the database");

                        engine.CreateDatabase();
                    }

                }
                CreateInitialDatabaseObjects(connString);

            }
        }
        private static void CreateInitialDatabaseObjects(string connString)
        {

            using (SqlCeConnection conn = new SqlCeConnection(connString))
            {
                string[] queries = Regex.Split(NetworkAssetManager.Properties.Resources.DBGenerateSql, "GO");
                SqlCeCommand command = new SqlCeCommand();
                command.Connection = conn;
                conn.Open();
                foreach (string query in queries)
                {
                    string tempQuery = string.Empty;
                    tempQuery = query.Replace("\r\n", "");

                    if (tempQuery.StartsWith("--") == true)
                    {
                        /*Comments in script so ignore*/ 
                        continue; 
                    }

                    _logger.Info("Executing query: " + tempQuery);

                    command.CommandText = tempQuery;
                    try
                    {
                        command.ExecuteNonQuery();
                    }
                    catch (System.Exception e)
                    {
                        _logger.Error(e.Message);
                    }
                }
                conn.Close();
            }
        }
    }
}
